using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Specialized;
using System.IO;

public partial class app_frame_Default2 : System.Web.UI.Page
{
    protected security hdds;
    public string sMessage = "";
    //DataSet dsPageEvents = null;
    string straddnewURL = "";
    string strPagesetRowId = "";

    protected void Page_PreInit(object sender, EventArgs e)
    {
        this.Theme = Session["Theme"].ToString();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        /*****Added By Dhanapal To handle Ajax Delete**********/
        string DeleteAjaxTreecall = Request.QueryString["DeleteAjaxTreeCall"] != null ? Request.QueryString["DeleteAjaxTreeCall"].ToString() : "false";
        Master MA = new Master();
        string strDelKey = "";
        if (DeleteAjaxTreecall.ToUpper().Trim() == "TRUE")
        {
            strPagesetRowId = Request.QueryString["pgs_id"].ToString();
            strDelKey = Request.QueryString["DPK"].ToString();
            Session["DPK"] = strDelKey;

            DataSet dsePageInfo = new DataSet();
            PageInfoLoad PIL = new PageInfoLoad();
            dsePageInfo = PIL.GetPageSetPageCtrlInfo(strPagesetRowId);

            bool blnStatus = MA.ProcessOperation(dsePageInfo, strDelKey, "DELETE");
            Session["DPK"] = null;

            Response.Clear();
            if (blnStatus)
                Response.Write("true");
            else
                Response.Write("false");
            Response.End();
        }
        /******End**********************/
        CheckForDefaultDashboards();
        if (IsPostBack)
        {
            btnfilter.Visible = true;
            lnkBtnViewAll.Visible = false;
            lblListHeader.Text = "";
            ScriptManager.RegisterStartupScript(this, this.GetType(), "filterdisableinvokeagain", "mb_disableFilterInvokeButton();", true);
        }
        else
            txtObjectSearch.Attributes.Add("onkeydown", "javascript:return interceptObjectSearch(event);");  // Modified by 'Imran Gani' on 10-Dec-2013, (this -> event) to get enter key value from event
        Session["datasort"] = hfSort.Value;
        destroyUnwantedObjects();
        Navigator.storeURL(Request.Url.ToString(), IsPostBack, false, true);//implemenetd by sanal on April 03, 2008
        this.Title = "MaxBlox";
        this.hdds = new security();
        if (Session["userid"] == null || Session["userid"].ToString() == "") Response.Redirect(hdds.SessionExpiryURL);
        DynamicDisplayI DDI = new DynamicDisplayI();
        HtmlForm frmObj = (HtmlForm)this.Master.FindControl("Form1");//HtmlForm frmObj = (HtmlForm)this.FindControl("Form1")
        if (MA.DeleteMessage != "")
        {
            lblMessage.Text = wrapItAsMessage(MA.DeleteMessage, true);
            MA.DeleteMessage = "";
        }
        else
            lblMessage.Text = "";
        string strErrorMsg = ""; // Added by 'Imran Gani' on 19-Jun-2014, for validate URL
        if (!hdds.IsValidPageURL(ref strErrorMsg))
        {
            lblMessage.Text = wrapItAsMessage(strErrorMsg, true);
            table1.Visible = false;
            return;
        }
        if (!IsPostBack)
        {
            GetEditPage();  // Added by srivatsan to avoid postback on Add New 
            btnAddNewTop.Attributes.Add("onclick", "javascript:disableThis('ctl00_ContentPlaceHolder3_btnAddNewTop','Loading...'); disableThis('ctl00_ContentPlaceHolder3_btnAddNew','Loading...'); window.location.href=('" + straddnewURL + "');");
            //btnAddNew.Attributes.Add("onClick", "javascript:disableThis('ctl00_ContentPlaceHolder3_btnAddNew','Loading...'); disableThis('ctl00_ContentPlaceHolder3_btnAddNewTop','Loading...'); window.location.href=('" + straddnewURL + "')");
            GetPageViewType();//Added By Dhanapal to Fill the Page View Type Drop Down.
        }
        hdds.logMenuClick(Request.QueryString["mn"].ToString());
        if (Request.QueryString["pgs_id"] != null)
            strPagesetRowId = Request.QueryString["pgs_id"].ToString();
        string strPageSetHeading = CommonFunctions.GetColValueFromPageInfo(strPagesetRowId, "sy_pgs", "pageset_name", "af_row_id='" + strPagesetRowId.Replace("'", "''") + "'");
        if (strPageSetHeading == "")
            strPageSetHeading = hdds.hddb.GetColumnValue("sy_pgs", "pageset_name", "af_row_id='" + strPagesetRowId.Replace("'", "''") + "'");
        lblHeading.Text = "&nbsp;" + GetPageIcons(strPagesetRowId).Text + "&nbsp;<span style='vertical-align:bottom;'>" + strPageSetHeading + "</span>&nbsp;"; // Modified by srivatsan
        PlaceHolder ph_page_caption = (PlaceHolder)DDI.FindControl(frmObj.Controls, "ph_page_caption");//PlaceHolder ph_page_caption = (PlaceHolder)frmObj.FindControl("ph_page_caption");
        ph_page_caption.Controls.Add(lblHeading);
        if (hihDeleteClick != null)
            if (hihDeleteClick.Value != "0")
                if (hihDeleteafrowid.Value != "")
                {
                    strDelKey = hihDeleteafrowid.Value;
                    Session["DPK"] = strDelKey;
                }
        if (strDelKey != "")
        {
            DataSet dsePageInfo = new DataSet();
            PageInfoLoad PIL = new PageInfoLoad();
            dsePageInfo = PIL.GetPageSetPageCtrlInfo(strPagesetRowId);
            //Master MA = new Master();
            if (Request.QueryString["cp"] != null)
            {
                HtmlInputHidden hihObj = (HtmlInputHidden)DDI.FindControl(frmObj.Controls, "hihCurrentPageId");//HtmlInputHidden hihObj = (HtmlInputHidden)frmObj.FindControl("hihCurrentPageId");
                hihObj.Value = Request.QueryString["cp"];
                //Request.QueryString.Remove("cp");
            }
            bool blnStatus = MA.ProcessOperation(dsePageInfo, strDelKey, "DELETE");
            Session["DPK"] = null;
            //Response.Clear();// added by sanal for delete refresh issue on Mar 24 2009 
        }
        if (strPagesetRowId != "")
        {
            string strddlValue = "";
            DropDownList ddl = (DropDownList)DDI.FindControl(frmObj.Controls, "ddlPageViewType");
            if (!IsPostBack && Request.QueryString["pgtype"] != null && Request.QueryString["pgtype"].ToString() != "")
            { // Added by 'Imran Gani' on 27-Jun-2013, to check a parameter for page view type in URL
                strddlValue = Request.QueryString["pgtype"].ToString();
                ddl.SelectedValue = strddlValue;
            }
            else
            {
                if (ddl != null)
                    strddlValue = ddl.SelectedValue.ToString();
            }
            if ((strddlValue == "LV" || strddlValue == "") && !IsPostBack) // Added by 'Imran Gani' on 24-Sep-2014, auto scroll ability for loading records
            {
                hfObjectRowID.Value = hdds.hddb.GetColumnValue("select af_row_id from sy_obj where object_id in (select object_id from sy_pgs_mem where pageset_id = '" + strPagesetRowId.Replace("'", "''") + "');");
                panelDynamicTree.Visible = false;
                return;
            }
            GridPaging GP = new GridPaging();
            if (strddlValue == "CV")  // Added By Dhanapal On Feb 10 2011 For category View
            {
                if (!GP.DisplayPage(strPagesetRowId, frmObj))
                    displayMessage(wrapItAsMessage("You do not have sufficient access permission.", true), "CV");
            }
            else
            {
                if (!GP.DisplayPage(strPagesetRowId, frmObj))
                {
                    if (strddlValue == "TV")
                        displayMessage(wrapItAsMessage("You do not have sufficient access permission.", true), "TV");
                    else
                        displayMessage(wrapItAsMessage("Error in retrieving the data.", true), "");
                }
                else if (panelDynamicGrid.Visible == false) //Added By Dhanapal
                {
                    if (panelDynamicTree.Controls.Count <= 7)
                        if (strddlValue == "TV" || strddlValue == "")
                            displayMessage(wrapItAsMessage("Error in retrieving the data.", true), "TV");
                }
                else if (tdDisplayGrid.Controls.Count == 1)
                {
                    if (strddlValue == "LV" || strddlValue == "") // Added by 'Imran Gani' on 24-Sep-2014, auto scroll ability for loading records
                    { }// ScriptManager.RegisterStartupScript(this, this.GetType(), "listpage", "getDataList('', null);", true);
                }
            }
        }
        //code added by Sampath for IPP on 14-Oct-2011
        if (Session["client_application"] != null)
            if (Session["client_application"].ToString().ToLower() == "ipp")
                hideAddButtons();
    }

    private string getContent(string fileName)
    {
        try
        {
            if (!File.Exists(fileName)) return "";
            string temp = "";
            StreamReader sr = new StreamReader(fileName);
            temp = sr.ReadToEnd();
            sr.Close(); sr = null;
            return temp;
        }
        catch (Exception e)
        {
            return "";
        }
    }

    private void hideAddButtons()
    {
        try
        {
            if (Request.Url.ToString().IndexOf("pgs_id=7774616db93f6bca") > -1 || Request.Url.ToString().IndexOf("pgs_id=8c2cb032c3b3516d") > -1)
            {
                //btnAddNew.Visible = false;
                btnAddNewTop.Visible = false;
                if (Request.Url.ToString().IndexOf("pgs_id=7774616db93f6bca") > -1)
                    tdAddButton.Controls.Add(new LiteralControl(getContent(HttpContext.Current.Server.MapPath("") + @"\repinfo.txt")));
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("hideAddButtons: Error: " + ex.Message);
        }
    }

    private string wrapItAsMessage(string msg, bool isError)
    {
        return "<div class=\"" + (isError == true ? "mbErrorMessage" : "mbMessage") + "\">" + msg + "</div>";
    }
    private void destroyUnwantedObjects()//implemented by sanal on 27 Feb 2008
    {
        //return;
        string[] strSessionNames = new string[] { "ReportInput", "dseObjectInputInfo", "dsePageInputInfo", "dsePagesetInputInfo" ,"dseTempInputInfo", "dtWorkflow" };
        for (int i = 0; i < strSessionNames.Length; i++)
            destroyObject(strSessionNames[i]);
        
    }
    private void destroyObject(string name)
    {
        try
        {
            if (Session[name]!=null)
                Session[name] = null;
        }
        catch (Exception e)
        {
        }
    }
    private void displayMessage(string sMessage ,string key) //Changed By Dhanapal
    {
        Label lblMessage1 = new Label();
        lblMessage1.Text = sMessage;
        lblMessage1.ForeColor = System.Drawing.Color.Red;
        if (key == "TV")
            panelDynamicTree.Controls.Add(lblMessage1);
        else if (key == "CV")
        {
            panelDynamicCategory.Attributes.Add("class", "dynamicTreeholder");
            panelDynamicCategory.Controls.Add(lblMessage1);
        }
        else
            tdDisplayGrid.Controls.Add(lblMessage1);
        btnAddNewTop.Visible = false;
    }

    protected void MenuItemClick(object sender, MenuEventArgs e)
    {
        Response.Write("Menu couldnt found");
        Response.Redirect("DisplayGrid.aspx?pgs_id=" + Request.QueryString["pageset_id"].ToString() + "&mid=" + Request.QueryString["pageset_id"].ToString());
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        string strPagesetRowId = Request.QueryString["pgs_id"].ToString();
        string strMenuRowId = Request.QueryString["mn"].ToString();
        //added for static page list view AddNew
        string sEditPage = "DynamicScreen.aspx";
        HDDatabase HDD = new HDDatabase();
        GenerateGrid objGD = new GenerateGrid();
        sEditPage = objGD.getEditPage(HDD, strMenuRowId);
        //
        if (sEditPage != "")
        {
            string strPageUrl = sEditPage + "?pgs_id=" + strPagesetRowId + "&mn=" + strMenuRowId;
            Response.Redirect(strPageUrl);
        }
    }

    private Literal GetPageIcons(string strPagesetRowID) // Added by srivatsan for Icon Display in Grids
    {
        Literal iconlit = new Literal();
        PageIcons icons = new PageIcons();
        try
        {
            string iconpath = icons.geticonsfrompageset(strPagesetRowID.Replace("'", "''"), 2);
            icons = null;
            iconlit.Text = "&nbsp;<img src = " + iconpath + " style='vertical-align:middle;'></img>&nbsp;";
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error GetPageIcons:" + ex.Message);
            iconlit.Text = "&nbsp;<img src = " + PageIcons.strdefaulticon.ToString() + "></img>&nbsp; ";
        }
        finally
        {
            icons = null;
        }
        return iconlit;
    }

    private void GetEditPage()
    {
        if (straddnewURL == "")
        {
            string strPagesetRowId = Request.QueryString["pgs_id"].ToString();
            string strMenuRowId = Request.QueryString["mn"].ToString();

            string strPageUrl = "";
            //added for static page list view AddNew
            string sEditPage = "DynamicScreen.aspx";
            HDDatabase HDD = new HDDatabase();
            GenerateGrid objGD = new GenerateGrid();
            sEditPage = objGD.getEditPage(HDD, strMenuRowId);
            //
            if (sEditPage != "")
            {
                strPageUrl = sEditPage + "?pgs_id=" + strPagesetRowId + "&mn=" + strMenuRowId;
                //Response.Redirect(strPageUrl);
            }
            straddnewURL = strPageUrl;
        }
        //hiheditpageURL.Value = strPageUrl;
    }

    private void GetPageViewType() //Added By Dhanapal On DEC292010 For Page View Type
    {
        string strPagesetRowId = Request.QueryString["pgs_id"].ToString();
        string strMenuRowId = Request.QueryString["mn"].ToString();
        //strPagesetRowId = "";
        if (strPagesetRowId.ToString().Trim() == "")
        {
            PageViewtypeholder.Visible = false; 
            return;
        }
        HDDatabase HDD = new HDDatabase();
        try
        {
            string strsql1 = "select mem_seq as mem_seq ,mem_id as ListType , mem_name as ListView from sy_acr_mem where acr_id = '67f864457589b041' and mem_seq = 1 union select sam.mem_seq as mem_seq , spm.mode as ListType , sam.mem_name as ListView from sy_pgs_mode spm inner join sy_acr_mem sam on spm.mode = sam.mem_id where spm.pageset_id = '" + strPagesetRowId + "';";
            DataSet ds = HDD.GetDataset(strsql1); // Modified by 'Imran Gani' on 08/05/12, where added a query in above sql for dataset, to get default grid view from menu designer.
            if ( ds.Tables[0].Rows.Count > 1 )
            {
                ddlPageViewType.DataSource = ds.Tables[0].DefaultView;
                ddlPageViewType.DataTextField = "ListView";
                ddlPageViewType.DataValueField = "ListType";
                ddlPageViewType.DataBind();
                string strMenuClick = CommonFunctions.GetColValueFromPageInfo(strPagesetRowId, "sy_mnu", "menu_click", "af_row_id = '" + strMenuRowId + "'");
                getDefaultGridView(ds, strMenuClick); // Added by 'Imran Gani' on 08/05/12, to set the default grid view.
            }
            else
            {
                PageViewtypeholder.Visible = false;
            }
        }
        catch (Exception e1)
        {
            LogWriter.WriteLog("Error in GetPageViewType:" + e1.Message);
        }
        finally
        {
            HDD = null;
        }
    }
    /// <summary>
    /// To Get the Default View of Display Grid for a Page.
    /// </summary>
    /// <param name="ds">DropDownList Table from Configuration and Menu_click Table from Menu Designer</param>
    private void getDefaultGridView(DataSet ds, string strMenuClick) // Added by 'Imran Gani' on 08/05/12, to set the default grid view.
    {
        try
        {
            //string strMenuClick = ds.Tables[1].Rows[0]["menu_click"].ToString();
            string temp = (strMenuClick == "3") == true ? "TV" : (strMenuClick == "4") == true ? "CV" : (strMenuClick == "5") == true ? "DS" : ""; // Modified by 'Imran Gani' (copied from RakaTech) on 27-May-2014, for Datasheet
            if (temp != "")
            {
                DataRow[] dr = ds.Tables[0].Select("ListType='" + temp + "'");
                if (dr != null && dr.Length > 0)
                    ddlPageViewType.SelectedValue = dr[0]["ListType"].ToString();
            }
        }
        catch (Exception e1)
        {
            LogWriter.WriteLog("Error in getDefaultGridView: " + e1.Message);
        }
    }

    protected void btnfilter_Click(object sender, EventArgs e)
    {
    }

    /// <summary>
    /// This will navigate to default dashboard if the current logged in user has one
    /// </summary>
    private void CheckForDefaultDashboards()
    {
        security hdds = new security();
        try
        {
            if (Request.QueryString["pgs_id"] != null)
                if (Request.QueryString["pgs_id"].ToString().ToLower() == "ca08b1b6c96f9950") // dashboard_master
                        if (hdds.GetDefaultDashboard().Trim() != "")
                            if (Request.QueryString["DBD"] == null)
                                    Response.Redirect(hdds.GetDashboardNavigateURL(Request.QueryString["mn"], Request.QueryString["pgs_id"]));
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : CheckForDefaultDashboards:"+ ex.Message);
        }
        finally
        {
            hdds = null;
        }
    }
    protected void btnAddNewTop_ServerClick(object sender, EventArgs e)
    {
    }
}
